package com.example.demo.hotel.service.impl;

import com.example.demo.hotel.entity.Order;
import com.example.demo.hotel.repository.OrderRepository;
import com.example.demo.hotel.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.List;
import java.util.Optional;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderRepository orderRepository;

    @Override
    public Order saveOrder(Order order) {
        return orderRepository.save(order);
    }

    @Override
    public Optional<Order> getOrderById(Long id) {
        return orderRepository.findById(id);
    }

    @Override
    public Order getOrderByOrderNo(String orderNo) {
        return orderRepository.findByOrderNo(orderNo);
    }

    @Override
    public Page<Order> getAllOrders(Pageable pageable) {
        return orderRepository.findAll(pageable);
    }

    @Override
    public List<Order> getOrdersByRoomNumber(String roomNumber) {
        return orderRepository.findByRoomNumber(roomNumber);
    }

    @Override
    public List<Order> getOrdersByDateRange(LocalDate startDate, LocalDate endDate) {
        return orderRepository.findByCheckInDateBetween(startDate, endDate);
    }

    @Override
    public List<Order> getOrdersByStatus(String status) {
        return orderRepository.findByStatus(status);
    }

    @Override
    public Page<Order> searchOrders(String keyword, Pageable pageable) {
        return orderRepository.findByOrderNoContainingOrCustomerNameContainingOrRoomNumberContaining(
            keyword, keyword, keyword, pageable);
    }

    @Override
    public Order updateOrder(Long id, Order orderDetails) {
        return orderRepository.findById(id)
                .map(order -> {
                    order.setOrderNo(orderDetails.getOrderNo()); // 添加订单号更新
                    order.setCustomerName(orderDetails.getCustomerName());
                    order.setRoomType(orderDetails.getRoomType()); // 添加房间类型更新
                    order.setRoomNumber(orderDetails.getRoomNumber());
                    order.setCheckInDate(orderDetails.getCheckInDate());
                    order.setCheckOutDate(orderDetails.getCheckOutDate());
                    order.setTotalPrice(orderDetails.getTotalPrice());
                    order.setStatus(orderDetails.getStatus());
                    return orderRepository.save(order);
                })
                .orElseThrow(() -> new RuntimeException("Order not found with id: " + id));
    }

    @Override
    public void deleteOrder(Long id) {
        orderRepository.deleteById(id);
    }
}